package com.pj.compose

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.blankj.utilcode.util.ToastUtils
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.pj.compose.activity.BluetoothActivity
import com.pj.compose.common.config.StringExt.debugPrint
import com.pj.compose.model.MainTabs
import com.pj.compose.ui.compose.BottomIcon
import com.pj.compose.ui.theme.*
import com.pj.compose.ui.theme.CustomThemeManager.WithTheme


val themeTypeState = mutableStateOf(ThemeType.Default)
val darkThemeState = mutableStateOf(false)

class MainActivity : ComponentActivity() {
    private val bluetoothPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it)
                startActivity(Intent(this, BluetoothActivity::class.java))
            else
                ToastUtils.showLong("请先赋予蓝牙权限")
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val themType: ThemeType by themeTypeState
            val isDarkTheme: Boolean by darkThemeState
            WindowCompat.setDecorFitsSystemWindows(window, false)
            WithTheme(type = themType, darkTheme = isDarkTheme) {
                rememberSystemUiController().setStatusBarColor(
                    Color.Transparent, darkIcons = !darkThemeState.value
                )
                MainPage(navController = rememberNavController())
            }
        }
    }

    fun startBluetoothActivity() {
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            Manifest.permission.BLUETOOTH_CONNECT
        } else {
            Manifest.permission.BLUETOOTH
        }
        if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED)
            bluetoothPermissionLauncher.launch(permission)
        else
            startActivity(Intent(this, BluetoothActivity::class.java))
    }

}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainPage(navController: NavHostController) {
    val tabs = MainTabs.values()
    var selectedItem by remember { mutableStateOf(0) }
    val itemColors = listOf(c666666, c3367D5)
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route ?: MainTabs.WIDGET_TAB.route
    val routes = remember { MainTabs.values().map { it.route } }
    Scaffold(
        modifier = Modifier
            .windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Bottom))
            .fillMaxSize(),
        bottomBar = {
            if (currentRoute in routes) {
                BottomNavigation(backgroundColor = Color.White) {
                    tabs.forEachIndexed { index, tab ->
                        val isSelect = selectedItem == index
                        val click = {
                            selectedItem = index
                            if (tab.route != currentRoute) {
                                navController.navigate(tab.route) {
                                    "当前路由：${tab.route}--$currentRoute".debugPrint()

                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                            }
                        }
                        BottomNavigationItem(
                            selected = isSelect,
                            onClick = click,
                            alwaysShowLabel = true,
                            icon = {
                                BottomIcon(
                                    id = tab.icon,
                                    colorList = itemColors,
                                    isSelect = isSelect,
                                    contentDescription = tab.tabName
                                )
                            },
                            label = {
                                Text(
                                    text = tab.tabName,
                                    color = itemColors[if (isSelect) 1 else 0],
                                    fontSize = 12.sp
                                )
                            })
                    }
                }
            }
        }
    ) {
//        Text(text = "12323343214124124", modifier = Modifier.padding(it))
        it
        NavGraph(
            navController = navController,
//            modifier = Modifier.padding(it),
        )
    }
}

/*

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    AppTheme {
        MainPage(rememberNavController())
    }
}*/
